package com.ruoyi.system.Utils.DataHandler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Random;

/**
 * 基于文件的端口数据处理逻辑
 */
public class FilePortDataHandler implements PortDataHandler{

    static String WorkPath = System.getProperty("user.home") + "/Desktop/HighSpeedFlow/work/";


    @Override
    public boolean send(byte[] data, int inPort, String fileName) throws IOException {
        String directoryPath = WorkPath + inPort + "/in";
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            boolean r = directory.mkdirs(); // 创建目录
            if(!r) {
                System.out.println("创建目录失败");
            }
        }

        // 创建文件路径
        fileName = "data_" + fileName + ".bin"; // 使用时间戳来避免文件名冲突
        File file = new File(directoryPath, fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(data); // 写入数据到文件
        } catch (IOException e) {
            e.printStackTrace();
            return false; // 发送失败
        } finally {
            if(fos != null) {
                fos.close();
            }
        }
        String dictName = WorkPath + inPort + "/in/dict.bin";
        updateDictFile(dictName, fileName);
        return true; // 发送成功
    }

    @Override
    public byte[] receive(int outPort) {
        String directoryPath = WorkPath + outPort + "/out";
        File directory = new File(directoryPath);

        // 确保目录存在
        if (!directory.exists()) {
            return new byte[0];
        }

        // 获取目录下所有文件，并找到第一个.bin文件
        File[] files = directory.listFiles((dir, name) -> name.endsWith(".bin"));
        if (files == null || files.length == 0) {
            return new byte[0];
        }
        File binFile = files[0]; // 假设只处理第一个.bin文件

        try {
            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(binFile.toPath());

            // 删除文件
            if (!binFile.delete()) {
                throw new IOException("Failed to delete the file: " + binFile.getAbsolutePath());
            }

            // 返回文件内容
            return fileContent;
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，例如返回空数组或抛出异常
            return new byte[0];
        }
    }

    public int countBinFiles(int outPort) {
        String directoryPath = WorkPath + outPort + "\\out";
        File directory = new File(directoryPath);
        // 确保目录存在
        if (!directory.exists() || !directory.isDirectory()) {
            return 0;
        }

        // 使用FilenameFilter来过滤.bin文件
        File[] binFiles = directory.listFiles((dir, name) -> name.endsWith(".bin"));
        return binFiles != null ? binFiles.length : 0;
    }

    public boolean createOutFile(byte[] data, int inPort, String fileName) throws IOException {
        String directoryPath = WorkPath + inPort + "/out";
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            boolean r = directory.mkdirs(); // 创建目录
            if(!r) {
                System.out.println("创建目录失败");
            }
        }

        // 创建文件路径
        fileName = "data_" + fileName + ".bin"; // 使用时间戳来避免文件名冲突
        File file = new File(directoryPath, fileName);
        Random random = new Random();
        int sleep = 30 + random.nextInt(271);
        FileOutputStream fos = null;
        try {
            Thread.sleep(sleep);
            fos = new FileOutputStream(file);
            fos.write(data); // 写入数据到文件
        } catch (IOException e) {
            e.printStackTrace();
            return false; // 发送失败
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if(fos != null) {
                fos.close();
            }
        }

        return true; // 发送成功
    }


    private void updateDictFile(String dictFilePath, String fileName) throws IOException {
        // 确保dict.bin文件存在
        File dictFile = new File(dictFilePath);
        if (!dictFile.exists()) {
            try (FileOutputStream fos = new FileOutputStream(dictFile)) {
                // 写入文件头或其他初始信息（如果需要）
            }
        }

        // 将新文件名追加到dict.bin中
        try (FileOutputStream fos = new FileOutputStream(dictFile, true)) {
            fos.write(fileName.getBytes());
            fos.write('\n');
        }
    }
}
